import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutterxc/module/common_module.dart';
import 'package:flutterxc/module/gridnav_module.dart';
import 'package:flutterxc/module/sales_box_module.dart';
import 'package:flutterxc/pages/search_paeg.dart';
import 'package:flutterxc/widget/sales_box.dart';
import 'package:flutterxc/widget/sub_nav.dart';
import 'package:flutterxc/widget/webview.dart';
import '../dao/home_dao.dart';
import 'package:flutterxc/widget/search_bar.dart';
//import 'dart:convert';

import 'package:flutterxc/widget/grid_nav.dart';
import 'package:flutterxc/widget/local_nav.dart';
import 'package:flutterxc/widget/loading_container.dart';
import 'package:flutterxc/pages/speak_page.dart';
class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  double appBarAlpha = 0;
  bool loading = true;
  List img_list = [
    'http://pages.ctrip.com/commerce/promote/20180718/yxzy/img/640sygd.jpg',
    'http://pages.ctrip.com/commerce/promote/20180718/yxzy/img/640sygd.jpg',
    'http://pages.ctrip.com/commerce/promote/20180718/yxzy/img/640sygd.jpg',
  ];
  List<CommonModel> localNavList;
  GridNavModel _gridNavModel;
  List<CommonModel> _subNavList;
  SalesBoxModel _salesBoxModel;
  List<CommonModel> bannerList = [];
  Future<Null> loadData() async{
    try {
      var res = await HomeDao.fetch();
//      print('${json.encode(res) }  res');
      setState(() {
        localNavList = res.localNavList;
        _gridNavModel = res.gridNav;
        _subNavList = res.subNavList;
        _salesBoxModel = res.salesBox;
        bannerList = res.bannerList;
        loading = false;
      });
        print(res.gridNav);
    }catch (err) {
      setState(() {
        loading = false;
      });
      throw err;
    }

//    return Null;
  }
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    loadData();
//    print('$res 6666666666666666666666666');
  }

//滚动方法
  void _onScroll(offset) {
    double alpha = offset / 100;
    if (alpha > 1.0) {
      alpha = 1.0;
    } else if (alpha < 0.0) {
      alpha = 0.0;
    }
    setState(() {
      appBarAlpha = alpha;
    });
//    print(offset);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFf2f2f2),
      body: LoadingContainer(isLoading: loading,child:  MediaQuery.removePadding(
        context: context,
        removeTop: true,
//        监听滚动 类
        child: NotificationListener(
          // ignore: missing_return
            onNotification: (scrollNotification) {
//            print(scrollNotification);
//          限制 数据0时 发生的事件 && 限制 事件源的深度在 0 第一位，避免轮播图误触
              if (scrollNotification is ScrollUpdateNotification &&
                  scrollNotification.depth == 0) {
                _onScroll(scrollNotification.metrics.pixels);
              }
            },
            child: Stack(
              children: <Widget>[
                RefreshIndicator(
                  onRefresh: (){
                   return loadData();
                  },
                  child: _listview,
                ),
                _appbar
              ],
            )),
      ),)
     ,
    );
  }
 Widget get _listview {
    return ListView(
      children: <Widget>[
        _barnner,
        Padding(
          padding: EdgeInsets.all(10),
          child: LocalNav(localNavList:localNavList ,),
        ),
        Padding(
          padding: EdgeInsets.all(10),
          child: GridNav(gridNavModel: _gridNavModel,),
        ),
        Padding(
          padding: EdgeInsets.all(10),
          child: SubNav(subNavList: _subNavList,),
        ),
        Padding(
          padding: EdgeInsets.all(10),
          child: SalesBox(salesBox: _salesBoxModel),
        ),

//        SizedBox(
//          height: 800,
//          child: Text('占位sizebox'),
//        )
      ],
    );
  }
  Widget get _appbar {
    return Column(
      children: <Widget>[
        Container(
          decoration: BoxDecoration(
            gradient: LinearGradient(colors: [Color(0x66000000),Colors.transparent],
            begin: Alignment.topCenter,
              end: Alignment.bottomCenter
            ),
          ),
          child: Container(
//            padding: EdgeInsets.fromLTRB(0, 20, 0, 0),
            height: 80,
            decoration: BoxDecoration(
              color: Color.fromARGB((appBarAlpha * 255).toInt(), 255, 255, 255)
            ),
            child: SearchBar(
              searchBartype:appBarAlpha > 0.2? SearchBarType.homeLight:SearchBarType.home,
              inputBoxClick: _jumpToSearch,
              speakClick: _jumToSpeak,
              defaultText: '欢迎光临红浪漫~~',
              leftButtonClick: (){print('123back'); Navigator.pop(context);},
            ),
          ),
        ),
        Container(
          height: appBarAlpha>0.2? 2:0,
          decoration: BoxDecoration(
            boxShadow: [BoxShadow(color: Colors.black54,blurRadius: 1.5)]
          ),
        )
      ],
    );
//    return Opacity(
//      opacity: appBarAlpha,
//      child: Container(
//        width: double.infinity,
//        height: 70,
//        color: Colors.blue,
//        child: Column(
//          mainAxisAlignment: MainAxisAlignment.center,
//          children: <Widget>[
//            Text(
//              '首页',
//              textAlign: TextAlign.center,
//            )
//          ],
//        ),
//      ),
//    );
  }
  Widget get _barnner {
    return Container(
      height: 150,
      child: Swiper(
        autoplay: true,
        itemCount: bannerList.length,
        itemBuilder: (BuildContext context, int index) {
          return GestureDetector(

            onTap: (){
              CommonModel model = bannerList[index];
//              WebView(url: model.url,);
//              print('${bannerList[index].url}');
              Navigator.push(context, MaterialPageRoute(builder: (context) => WebView(url: model.url,)));
            },
            child: Container(
              height: 150,
              child:  Image.network(
                bannerList[index].icon,
                fit: BoxFit.cover,
              ),
            ),
          );
        },
        pagination: new SwiperPagination(),
        control: new SwiperControl(),
      ),
    );
  }
  _jumpToSearch(){
    Navigator.push(context, MaterialPageRoute(builder: (context) => SearchPage()));
  }
  _jumToSpeak(){
    Navigator.push(context, MaterialPageRoute(builder: (context) => SpeakPage()));
  }
}

